<?php

namespace App\Modules\Admin\Services\Water\Member;

use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Member\UserScoreModel;
use App\Modules\Admin\Entities\Vip\VipModel;
use App\Modules\Admin\Services\BaseService;
use DateTime;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;

class ScoreService extends BaseService
{
    public function __construct(UserScoreModel $model)
    {
        $this->model = $model;
        $this->with=['water_device_info'];
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
            if (!empty($uid = $request->input('uid', ''))){
                $query->where('user_id',$uid);
            }
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
        };

        return parent::lists($params); // TODO: Change the autogenerated stub
    }


    public function getScoreListDetails($params){
        $gift_id = $params['gift_id'];
        $lists = $this->model->with(['water_device_info','user_info'])->where(['gift_id'=>$gift_id,'is_delete'=>0])->get()->toArray();
        return $lists;
    }

    /**
     * 当前积分详情（提现只能当月以前，所以全都是flag=0的）
     * @param $uid
     * @return array
     */
    public function statistics($uid): array
    {
        //昨日积分
        $orm = UserScoreModel::where('user_id', $uid)->where('flag',self::GAIN);
        $yesterdayOrm = clone $orm; // 克隆对象避免冲突
        $yesterday = $yesterdayOrm
            ->where("created_at",">=",date('Y-m-d 00:00:00',strtotime("-1 day")))
            ->where("created_at","<=",date('Y-m-d 23:59:59',strtotime("-1 day")))
            ->sum('score');
        //累计获取
        $all = $orm->sum('score');
        [$startOfMonth,$endOfMonth] = getThisMonth(date("Y-m"));
        $monthOrm = clone $orm; // 克隆对象避免冲突
        $month = $monthOrm->where("created_at",">=",$startOfMonth)
            ->where("created_at","<=",$endOfMonth)
            ->sum('score');

        //积分本为3位小数，罗总2024年8月27日 15:11 确定显示整数（未考虑会出现负数积分场景）
        return [
            'yesterday' => floor($yesterday),
            'all' => floor($all),
            'month' => floor($month),
        ];
    }

    /**
     * @param $uid
     * @param $time
     * @param $page
     * @param $pageSize
     * @return array
     * @throws Exception
     */
    public function list($uid,$time,$page,$pageSize): array
    {
        [$startOfMonth,$endOfMonth] = getThisMonth($time);
        $threeMonthsAgo = (new DateTime())->modify('-3 months')->setTime(0, 0, 0);
        $givenDate = DateTime::createFromFormat('Y-m', $time)
            ->modify('first day of this month')->setTime(0, 0, 0);
        if($givenDate < $threeMonthsAgo) {
            error('仅支持查询三个月数据');
        }
        $orm = UserScore::where('user_id', $uid)
            ->where('created_at','>=',$startOfMonth)
            ->where('created_at','<=',$endOfMonth);
        $count = $orm->count();
        $list = $orm->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderBy('created_at','DESC')
            ->get();
        $data = [];
        foreach ($list as $item) {
            $data[] = [
                'id' => $item->id,
                'score' => floor($item->score),
                'flag' => $item->flag,
                'created_at' => $item->created_at,
            ];
        }
        return page($data,$page,$pageSize,$count);
    }

    /**
     * @param $uid
     * @return array
     */
    public function usable($uid): array
    {
        //罗总在2024年8月20日 15:51提出要求，仅能提现当月以前的
        [,$endOfMonth] = getThisMonth(date("Y-m",strtotime("-1 month")));
        [$start,$end] = getThisMonth(date("Y-m"));
        //当月已提现
        $take = UserScoreModel::where('user_id', $uid)
            ->where('flag',UserScoreModel::TAKE)
            ->where('created_at','>=',$start)
            ->where('created_at','<=',$end)
            ->sum('score');
        //当月之前的总分
        $score = UserScoreModel::where('user_id', $uid)
            ->where('created_at','<=',$endOfMonth)
            ->sum('score');

        return ['score'=>floor($score+$take)];//注意：已提现的为负数，所以相加，别改成相减，改了出bug请自抽。
    }

    /**
     * @param $uid
     * @param $score
     * @return bool
     * @throws Exception
     */
    public function take($id,$uid,$score): bool
    {
       /* if(!$id) {
            error('请选择银行卡');
        }
        if($score < 1) {
            error('申请额度最低为1积分');
        }
        $scoreInfo = /::usable($uid);
        $maxScore = Arr::get($scoreInfo,'score');
        if($score>$maxScore) {
            error('超出最大额度');
        }
        $data = [
            'user_id' => $uid,
            'score' => -$score,//注意：提现是负数，别改成正数，改了出bug请自抽。
            'flag' => UserScoreModel::TAKE,
        ];
        $bool = UserScoreModel::where('user_id', $uid)->create($data);
        if(!$bool){
            error('申请出错，请重试');
        }*/
        return true;
    }
}
